package com.sinosoft.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sinosoft.common.Const;
import com.sinosoft.util.PropertiesUtil;

/**
 * @description 登录Filter过滤
 * @author Jason Rao
 * @version 2017年9月26日 下午1:48:21
 */
public class AuthFilter implements Filter {

	private Logger logger = LoggerFactory.getLogger(getClass());
	
	@Override
	public void destroy() {
		logger.debug("{}过滤器销毁...", this.getClass());
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain arg2) throws IOException, ServletException {
		String[] excludePath = PropertiesUtil.get("exclude.path", "config.authConfig").split(",");
		HttpServletRequest request = (HttpServletRequest) req;
		for (int i = 0; i < excludePath.length; i++) {
			if (request.getRequestURI().endsWith(excludePath[i])) {
				arg2.doFilter(req, resp);
				return;
			}
		}
		HttpServletResponse response = (HttpServletResponse) resp;
		HttpSession session = request.getSession(false);
		if (null == session) {
			response.sendRedirect(request.getContextPath()+"/index.jsp");
			return;
		}
		Object user = session.getAttribute(Const.SESSION_USER_KEY);
		if (null == user) {
			response.sendRedirect(request.getContextPath()+"/index.jsp");
			return;
		} else {
			arg2.doFilter(req, resp);
			return;
		}
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		logger.debug("{}过滤器初始化...", this.getClass());
	}

}
